<template>
<view>
<userinfo id="user" :options="user_options" @getUserscope="getUserInfo" @toLogin="getUserInfo"></userinfo>
<view class="container">
    <form bindsubmit="buySubmit">
        <view class="h3">{{buy_detail.now_group.s_name}}</view>
        <view class="list bw">
            <view class="item cf">
                <view class="fl">单价：</view>
                <view class="fr">{{buy_detail.now_group.price}}元</view>
            </view>
            <view class="item cf">
                <view class="fl">数量：</view>
                <view class="fr">
                    <button class="btn minus" @tap="minNum" :disabled="(buy_num <= buy_detail.now_group.once_min ? true : false)">-</button>
                    <input type="number" name="quantity" class="number" :value="buy_num" @input="changeNum"></input>
                    <button class="btn plus" @tap="plusNum" :disabled="(buy_detail.now_group.once_max != 0 && buy_num >= buy_detail.now_group.once_max ? true : false)">+</button>
                </view>
            </view>
            <view class="item cf">
                <view class="fl">总价：</view>
                <view class="fr fw cr">{{total_price}}元</view>
            </view>
        </view>
        <block v-if="buy_detail.now_group.tuan_type != 2">
            <view class="h4">您绑定的手机号码</view>
            <view class="list bw">
                <view class="item cf">
                    <view class="fl">{{buy_detail.user.phone}}</view>
                </view>
            </view>
        </block>
        <block v-else>
            <view class="h4">选择收货地址</view>
            <view class="bw pickBox">
                <view class="title btm2f1">
                    <text>配送方式</text>
                    <view :class="'btn_express fr ' + (nowPickType == 'pick' ? 'active' : '')" data-type="pick" @tap="changePick" v-if="buy_detail.now_group.pick_in_store == 1">到店自提</view>
                    <view :class="'btn_express fr ' + (nowPickType == 'express' ? 'active' : '')" data-type="express" @tap="changePick">快递配送</view>
                </view>
                <view class="address" v-if="nowPickType == 'express'" @tap="selectUserAddress">
                    <view class="row">姓名：{{buy_detail.user_adress[0].name}}</view>
                    <view class="row">手机：{{buy_detail.user_adress[0].phone}}</view>
                    <view class="row">地址：{{buy_detail.user_adress[0].province_txt}} {{buy_detail.user_adress[0].city_txt}} {{buy_detail.user_adress[0].area_txt}} {{buy_detail.user_adress[0].adress}} {{buy_detail.user_adress[0].detail}}</view>
                    <view class="row" v-if="buy_detail.user_adress[0].zipcode">邮编：{{buy_detail.user_adress[0].zipcode}}</view>
                </view>
                <view class="address" v-if="nowPickType == 'pick'" @tap="selectPickAddress">
                    <view class="row">地址：{{buy_detail.pick_address[0].name}}</view>
                    <view class="row">手机：{{buy_detail.pick_address[0].phone}}</view>
                    <view class="row">省市区：{{buy_detail.pick_address[0].province}} {{buy_detail.pick_address[0].city}} {{buy_detail.pick_address[0].area}}</view>
                </view>
            </view>
            <block v-if="nowPickType == 'express'">
                <view class="h4">选择送货时间</view>
                <view class="bw expressTimeBox">
                    <picker bindchange="expressTimeChange" :value="express_time_index" range-key="value" :range="buy_detail.delivery_time">
                        <view class="picker">{{buy_detail.delivery_time[express_time_index].value}}</view>
                    </picker>
                </view>
                <view class="h4">配送说明</view>
                <view class="bw commentBox">
                    <input type="text" name="delivery_comment" placeholder="配送特殊说明，配送公司会尽量调节"></input>
                </view>
            </block>
        </block>
        <button class="block_btn mlr20" form-type="submit">提交订单</button>
    </form>
</view>
</view>
</template>

<script>
import common from '../../utils/common.js'
var app = getApp();
var sysRes = {};
var rpxUnit = 0;
var go_action = '';
var _this;

export default {
  data() {
    return {
      group_id: 0,
      buy_detail: {},
      buy_num: 1,
      nowPickType: 'express',
      express_time_index: 0,
      total_price: 0
    };
  },
  onShow: function () {
    if (go_action == 'user_address') {
      var address_id = wx.getStorageSync('use_address_id');

      if (address_id) {
        var address_info = wx.getStorageSync('use_address_arr');
        wx.removeStorage({
          key: 'use_address_id'
        });
        wx.removeStorage({
          key: 'use_address_arr'
        });
        go_action = '';
        var buy_detail = this.buy_detail;
        buy_detail.user_adress[0] = address_info;
        this.setData({
          buy_detail: buy_detail
        });
        this.onReady();
      }
    } else if (go_action == 'pick_address') {
      var pick_id = wx.getStorageSync('pick_addr_id');

      if (pick_id) {
        var address_info = wx.getStorageSync('pick_addr_arr');
        wx.removeStorage({
          key: 'pick_addr_id'
        });
        wx.removeStorage({
          key: 'pick_addr_arr'
        });
        go_action = '';
        var buy_detail = this.buy_detail;
        buy_detail.pick_address[0] = address_info;
        this.setData({
          buy_detail: buy_detail
        });
        this.onReady();
      }
    } else if (go_action == 'bind_phone') {
      if (app.globalData.userInfo.phone == '') {
        wx.showModal({
          title: '温馨提示',
          content: '为了保护您的权益，下单前您需要绑定手机号码。',
          showCancel: false,

          success(res) {
            go_action = 'bind_phone';
            wx.navigateTo({
              url: '/pages/my/newnumber'
            });
          }

        });
      } else {
        common.post('Group&a=buy', {
          group_id: this.group_id,
          type: 1
        }, "setPageContent", this);
      }
    }
  },
  onLoad: function (options) {
    _this = this;
    common.setMainColor(_this);

    _this.setData({
      group_id: options.group_id
    });

    if (app.globalData.userInfo == null) {
      _this.setData({
        user_options: {
          toLogin: true,
          showCancel: false,
          refuseIsShow: true
        }
      });
    } else {
      _this.getPageInfo();
    }
  },
  methods: {
    expressTimeChange: function (e) {
      this.setData({
        express_time_index: e.detail.value
      });
    },
    selectPickAddress: function (e) {
      go_action = 'pick_address';
      wx.navigateTo({
        url: "../my/pick_address?pick_id=" + this.buy_detail.pick_address[0].pick_addr_id + '&mer_id=' + this.buy_detail.now_group.mer_id
      });
    },
    selectUserAddress: function () {
      var address_id = this.buy_detail.user_adress[0] ? this.buy_detail.user_adress[0].adress_id : 0;
      go_action = 'user_address';
      wx.navigateTo({
        url: "../my/address?address_id=" + address_id
      });
    },
    changePick: function (e) {
      this.setData({
        nowPickType: e.currentTarget.dataset.type
      });
    },
    buySubmit: function (e) {
      var postData = {};
      postData.group_id = this.group_id;
      postData.type = 2;
      postData.quantity = e.detail.value.quantity;

      if (this.buy_detail.now_group.tuan_type == 2) {
        if (this.nowPickType == 'express') {
          postData.delivery_type = this.buy_detail.delivery_time[this.express_time_index].key;
          postData.adress_id = this.buy_detail.user_adress[0].adress_id;
          postData.delivery_comment = e.detail.value.delivery_comment;
        } else if (this.nowPickType == 'pick') {
          var tmpArr = this.buy_detail.pick_address[0];
          postData.delivery_type = 1;
          postData.pick_in_store = 1;
          postData.pick_address = tmpArr.province + ' ' + tmpArr.city + ' ' + tmpArr.area + ' ' + tmpArr.name + ' 自提点电话：' + tmpArr.phone;
        }
      }

      console.log(postData); //return false;

      common.post('Group&a=buy', postData, "saveOrderResult", this);
    },
    saveOrderResult: function (res) {
      wx.navigateTo({
        url: "../pay/index?order_id=" + res.order.order_id + '&type=' + res.order.type
      });
    },
    changeNum: function (e) {
      var quantity = e.detail.value;

      if (quantity == '') {
        this.setData({
          total_price: 0
        });
        return;
      }

      if (quantity <= this.buy_detail.now_group.once_min) {
        quantity = this.buy_detail.now_group.once_min;
      } else if (this.buy_detail.now_group.once_max != 0 && quantity >= this.buy_detail.now_group.once_max) {
        quantity = this.buy_detail.now_group.once_max;
      }

      this.setData({
        buy_num: parseInt(quantity),
        total_price: (this.buy_detail.now_group.price * parseInt(quantity)).toFixed(2)
      });
    },
    minNum: function () {
      var buy_num = this.buy_num > this.buy_detail.now_group.once_min ? this.buy_num - 1 : this.buy_detail.now_group.once_min;
      this.setData({
        buy_num: buy_num,
        total_price: (this.buy_detail.now_group.price * buy_num).toFixed(2)
      });
    },
    plusNum: function () {
      console.log(123);
      var buy_num = this.buy_detail.now_group.once_max == 0 || this.buy_num < this.buy_detail.now_group.once_max ? this.buy_num + 1 : this.buy_detail.now_group.once_max;
      this.setData({
        buy_num: buy_num,
        total_price: (this.buy_detail.now_group.price * buy_num).toFixed(2)
      });
    },
    setPageContent: function (res) {
      var buy_num = parseInt(res.now_group.once_min); //res.now_group.once_max = 3

      res.now_group.price = parseFloat(res.now_group.price);
      this.setData({
        buy_detail: res,
        buy_num: buy_num,
        total_price: (res.now_group.price * buy_num).toFixed(2)
      });
      wx.hideToast();
      console.log(res);
    },

    getPageInfo() {
      common.post('Group&a=buy', {
        group_id: _this.group_id,
        type: 1
      }, "setPageContent", _this);

      if (app.globalData.userInfo.phone == '') {
        wx.showModal({
          title: '温馨提示',
          content: '为了保护您的权益，下单前您需要绑定手机号码。',
          showCancel: false,

          success(res) {
            go_action = 'bind_phone';
            wx.navigateTo({
              url: '/pages/my/newnumber'
            });
          }

        });
      }
    },

    getUserInfo(e) {
      if (e.detail.userInfo) {
        _this.getPageInfo();
      }
    },

    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
.h3{
    margin:20rpx 24rpx;
    font-size:32rpx;
}
.h4{
    margin:30rpx 24rpx 20rpx;
    font-size:28rpx;
}
.list{
    padding-left:20rpx;
}
.list .item{
    padding:22rpx 20rpx 22rpx 0;
    border-bottom: 1px solid #f1f1f1;
}
.list .btn{
    display: inline-block;
    text-align: center;
    color: #FF658E;
    border:2rpx solid #FF658E;
    height:60rpx;
    width:60rpx;
    line-height:60rpx;
    vertical-align: middle;
    background: white;
    padding:0;
}
.list .btn.button-hover{
    background:#FF658E;
    color:white;
}
.list .btn[disabled]{
    background-color: #dcdcdc;
    color: #999;
    border: 0;
}
.list .number{
    height: 60rpx;
    display: inline-block;
    vertical-align: middle;
    border: 2rpx solid #ddd8ce;
    border-radius: 10rpx;
    box-sizing: border-box;
    line-height:60rpx;
    width: 100rpx;
    text-align: center;
    margin:0 10rpx;
}



.pickBox .title{
    padding:20rpx 20rpx;
    line-height:56rpx;
}
.btn_express {
    background-color: #fff;
    border: 2rpx solid #4A96D4;
    font-weight: 300;
    text-decoration: none;
    text-align: center;
    padding: 0rpx 24rpx;
    line-height:52rpx;
    display: inline-block;
    cursor: pointer;
    box-sizing: border-box;
    transition-property: all;
    transition-duration: 0.3s;
    border-radius: 8rpx;
    margin-left:12rpx;
}
.btn_express.active{
    background-color: #4A96D4;
    color:white;
}
.pickBox .address{
    padding:20rpx 30rpx 20rpx 20rpx;
    position:relative;
}
.pickBox .address .row{
    line-height:1.7;
}
.pickBox .address:after {
    position: absolute;
    right: 20rpx;
    top: 50%;
    margin-top:-8rpx;
    display: block;
    content: '';
    width:12rpx;
    height:12rpx;
    border-left: 2rpx solid black;
    border-top: 2rpx solid black;
    transform: rotate(135deg);
}

.expressTimeBox .picker{
    padding:20rpx;
    font-size:24rpx;
    position:relative;
}
.expressTimeBox .picker:after{
    position: absolute;
    right: 30rpx;
    top: 50%;
    margin-top:-8rpx;
    display: block;
    content: '';
    width:12rpx;
    height:12rpx;
    border-left: 2rpx solid black;
    border-top: 2rpx solid black;
    transform: rotate(225deg);
}
.commentBox input{
    padding:20rpx;
    font-size:24rpx;
}
</style>